package database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * This class provide some utilities to manipulate files.
 * Check if this user can read and write a file.
 * Check if a file exists, and if not create it.
 * 
 * @author htrmeira@gmail.com
 */
public class PrepareFiles {
	
	/**
	 * This method tests if the passwd.xml file already exists, if not create a
	 * file. If exists, it will check if the user has permission of write and
	 * read, if it do not have, it will delete and create a new file.
	 * 
	 * @throws IOException When the file can not be loaded.
	 */
	public static void prepareFile(String file, String defaultMessage) throws IOException {
		File fileToCheck = new File(file);
		
		File db = new File("Database");
		if(!db.exists()) {
			db.mkdirs();
		}
		
		if (!fileToCheck.exists()) {
			createFile(file, defaultMessage);
		}
		
		if(!fileToCheck.canWrite() || !fileToCheck.canRead()) {
			fileToCheck.setWritable(true);
			fileToCheck.setReadable(true, true);
		}
	}
	
	/**
	 * This method tests if the passwd.xml file already exists, if not create a
	 * file. If exists, it will check if the user has permission of write and
	 * read, if it do not have, it will delete and create a new file.
	 * 
	 * @throws IOException When the file can not be loaded.
	 */
	public static void prepareFile(String file) throws IOException {
		File fileToCheck = new File(file);
		
		if (!fileToCheck.exists()) {
			createFile(file, "");
		}
		
		if(!fileToCheck.canWrite() || !fileToCheck.canRead()) {
			fileToCheck.setWritable(true);
			fileToCheck.setReadable(true, true);
		}
	}

	/**
	 * Create a new file in the path. This file is a .xml that
	 * <code>Properties</code> manipulates.
	 * 
	 * @param fileName The path and the name to the file.
	 * @throws IOException If the file was not created.
	 */
	private static void createFile(String fileName, String message) throws IOException {
		FileOutputStream outputFile = new FileOutputStream(fileName);
		Properties tempProperties = new Properties();
		tempProperties.storeToXML(outputFile, message);
		outputFile.close();
	}
}
